<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/5
 * Time: 下午6:37
 */

namespace EWeiLink\JuPai;


trait ModelBridgeTrait
{
    protected $_appInstance = null;

    public function __call($name, $arguments)
    {
        if (
            class_exists(static::appModelName)
            && method_exists(static::appModelName, $name)
        ) {
            if (is_null($this->_appInstance)) {
                $class_name = static::appModelName;
                $this->_appInstance = new $class_name($this->toArray());
            }
            return call_user_func_array([$this->_appInstance, $name], $arguments);
        }

        return parent::__call($name, $arguments);

//        throw new \BadMethodCallException("Not found method: $name");
    }

    static function __callStatic($name, $arguments)
    {
        if (
            class_exists(static::appModelName)
            && method_exists(static::appModelName, $name)
        ) {
           $class_name = static::appModelName;
           return call_user_func_array([$class_name, $name], $arguments);
        }
        $instance = new static;
        return call_user_func_array([$instance, $name], $arguments);
//        throw new \BadMethodCallException("Not found static method: $name");
    }

    /**
     * 直接实例化系统原始Model，如果不存在，则实例化插件Model
     * @param array $options
     * @return mixed
     */
    static function new(array $options = [])
    {
        if (class_exists(static::appModelName)) {
            $className = static::appModelName;
            return new $className($options);
        } else {
            return new static($options);
        }
    }

    /**
     * @return null
     */
    public function getAppInstance()
    {
        if (is_null($this->_appInstance)) {
            $className = static::appModelName;
            $this->_appInstance = (new $className)->find($this->id);
        }
        return $this->_appInstance;
    }

}